from db_DeviceManager import DeviceManager
from db_base import DatabaseManager, dbconfig


class RehabSystem:
    def __init__(self):
        # 初始化数据库连接
        self.DeviceManager=DeviceManager()
        self.db_manager = DatabaseManager(dbconfig)

    def __del__(self):
        # 确保资源释放
        self.db_manager.close()

    def get_role_dashboard_data(self, user_id, role):
        """
        获取角色专属的仪表盘数据
        参数:
            user_id: 用户ID
            role: 用户角色(doctor/therapist/patient)
        返回:
            包含各类数据的字典，失败返回空字典
        """
        data = {}
        try:
            if role == 'doctor':
                data.update({
                    'patients': self.get_therapist_patients(user_id),
                    'therapists': self.get_associated_therapists(user_id),
                })
            elif role == 'therapist':
                data.update({
                    'devices': self.DeviceManager.get_therapist_devices(user_id),
                    'active_plans': self.get_active_plans(user_id),
                    'upcoming_sessions': self.get_upcoming_sessions(user_id)
                })
            elif role == 'patient':
                data.update({
                    'active_plans': self.get_patient_plans(user_id),
                    'latest_feedback': self.get_latest_feedback(user_id),
                    'progress': self.get_patient_progress(user_id)
                })
        except Exception as e:
            print(f"仪表盘数据获取失败: {e}")
        return data

    def get_therapist_patients(self, doctor_id):
        """获取医生下的治疗师及其负责的患者列表"""
        query = """
            SELECT 
                pp.user_id AS patientid,
                pp.full_name AS patientname,
                pp.gender AS patientgender,
                TIMESTAMPDIFF(YEAR, pp.birth_date, CURDATE()) AS patientage,
                u.username AS therapistname
            FROM 
                patient_profiles pp
            JOIN 
                users u ON pp.doctor_id = u.user_id
            JOIN 
                doctor_therapist_relation dtr ON pp.doctor_id = dtr.therapist_id
            WHERE 
                dtr.doctor_id = %s
            GROUP BY 
                pp.user_id, pp.full_name, pp.gender, pp.birth_date, u.username;
            """
        return self.db_manager.execute_query(query, (doctor_id,)) or []

    def get_associated_therapists(self, doctor_id):
        """获取医生关联的治疗师"""
        query = """
        SELECT 
            t.user_id AS therapist_id, 
            t.username,
            COUNT(DISTINCT rp.plan_id) AS patient_count
        FROM doctor_therapist_relation dtr
        JOIN users t ON dtr.therapist_id = t.user_id
        LEFT JOIN rehabilitation_plans rp ON rp.therapist_id = t.user_id AND rp.status = 'active'
        WHERE dtr.doctor_id = %s
        GROUP BY t.user_id
        """
        return self.db_manager.execute_query(query, (doctor_id,))


    def get_active_plans(self, therapist_id):
        """获取治疗师负责的活跃计划"""
        query = """
        SELECT 
            rp.plan_id, 
            rp.plan_name, 
            u.username AS patient_name,
            rp.start_date,
            rp.end_date,
            rp.status,
            DATEDIFF(rp.end_date, CURDATE()) AS remaining_days
        FROM rehabilitation_plans rp
        JOIN users u ON rp.patient_id = u.user_id
        WHERE rp.therapist_id = %s AND rp.status = 'active'
        ORDER BY rp.end_date
        """
        return self.db_manager.execute_query(query, (therapist_id,))

    def get_upcoming_sessions(self, therapist_id):
        """获取即将开始的训练课程"""
        query = """
        SELECT 
            tr.record_id,
            u.username AS patient_name,
            te.exercise_type,
            tr.start_time
        FROM training_records tr
        JOIN users u ON tr.patient_id = u.user_id
        JOIN training_exercises te ON tr.exercise_id = te.exercise_id
        JOIN rehabilitation_plans rp ON te.plan_id = rp.plan_id
        WHERE rp.therapist_id = %s 
          AND tr.start_time > NOW()
          AND tr.start_time < DATE_ADD(NOW(), INTERVAL 7 DAY)
        ORDER BY tr.start_time
        LIMIT 5
        """
        return self.db_manager.execute_query(query, (therapist_id,))

    def get_patient_plans(self, patient_id):
        """获取患者的所有康复计划（带治疗师信息）"""
        query = """
        SELECT p.plan_id, p.plan_name, p.start_date, p.end_date,
               p.status, p.frequency, u.username AS therapist_name
        FROM rehabilitation_plans p
        JOIN users u ON p.therapist_id = u.user_id
        WHERE p.patient_id = %s
        ORDER BY p.start_date DESC
        """
        try:
            return self.db_manager.execute_query(query, (patient_id,))
        except Exception as e:
            print(f"获取患者康复计划失败: {e}")
            return None

    def get_latest_feedback(self, patient_id):
        """获取患者的最新反馈"""
        query = """
        SELECT 
            pf.rating,
            pf.comment,
            te.exercise_type,
            pf.submitted_at
        FROM patient_feedback pf
        JOIN training_records tr ON pf.record_id = tr.record_id
        JOIN training_exercises te ON tr.exercise_id = te.exercise_id
        WHERE tr.patient_id = %s
        ORDER BY pf.submitted_at DESC
        LIMIT 3
        """
        return self.db_manager.execute_query(query, (patient_id,))

    def get_patient_progress(self, patient_id):
        """获取患者的康复进度"""
        query = """
        SELECT 
            AVG(tr.completion_rate) AS avg_completion,
            AVG(pf.rating) AS avg_rating,
            COUNT(DISTINCT tr.record_id) AS total_sessions
        FROM training_records tr
        LEFT JOIN patient_feedback pf ON pf.record_id = tr.record_id
        WHERE tr.patient_id = %s
        """
        return self.db_manager.execute_query(query, (patient_id,))[0] if self.db_manager.execute_query(query, (
        patient_id,)) else None